﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ThinhTien.Common.Enums;
using DevExpress.Web.Mvc;
using ThinhTien.Data.Repository;
using ThinhTien.Models;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using System.Drawing;
using System.Web.UI;

namespace ThinhTien.Admin.Controllers
{
    public class UserController : BaseController
    {
        private UserRepository user = new UserRepository();

        public ActionResult Index()
        {
            Session["MenuItem"] = MenuItems.User;
            return View();
        }

        #region Upload File
        public ActionResult UploadUserImage(UserViewModel model)
        {
            var valid = new DevExpress.Web.ASPxUploadControl.ValidationSettings()
            {
                MaxFileSize = 400000
            };

            UploadControlExtension.GetUploadedFiles("uploadControl", valid, fileUploadComplete);
            return null;
        }

        private void fileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            var msResized = new MemoryStream();
            var resultFilePath = string.Empty;
            var resultFilePathClient = string.Empty;
            if (e.UploadedFile.IsValid)
            {
                try
                {
                    MemoryStream ms = new MemoryStream(e.UploadedFile.FileBytes);
                    Image originalImage = Image.FromStream(ms);
                    Image resizedImage = originalImage.GetThumbnailImage(150, (150 * originalImage.Height) / originalImage.Width, null, IntPtr.Zero);

                    resizedImage.Save(msResized, System.Drawing.Imaging.ImageFormat.Png);
                    Session["FileData"] = msResized.ToArray();

                    var fileName = string.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(e.UploadedFile.FileName));
                    resultFilePath = "~/Content/Temp/" + fileName;
                    resultFilePathClient = "~/Content/Temp/" + fileName;
                }
                catch
                {

                }

                using (FileStream file = new FileStream(Request.MapPath(resultFilePath), FileMode.CreateNew, FileAccess.Write))
                {
                    msResized.WriteTo(file);
                }
            }

            IUrlResolutionService urlResolver = sender as IUrlResolutionService;
            if (urlResolver != null)
                e.CallbackData = String.Format("{0}?refresh={1}", urlResolver.ResolveClientUrl(resultFilePathClient), Guid.NewGuid());
        }
        #endregion

        #region CRUD
        [HttpPost]
        public ActionResult AddUser(UserViewModel model)
        {
            var photo = Session["FileData"] as byte[];
            if (photo != null)
                model.Photo = photo;

            if (ModelState.IsValid)
            {
                ViewData["EditingRowKey"] = model.ID;

                if (user.IsExisted(model.UserName))
                {
                    ViewData["EditError"] = string.Format("<b>{0}</b> was existed in the system.", model.UserName);
                }
                else
                {
                    try
                    {
                        user.AddNew(model);
                        Session["FileData"] = null;
                    }
                    catch (Exception ex)
                    {

                    };
                }
            }

            ViewData["UserViewModel"] = model;

            return UserRowPartial();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult UpdateUser(UserViewModel model)
        {
            ViewData["EditingRowKey"] = model.ID;

            if (ModelState.IsValid)
            {
                try
                {
                    var photo = Session["FileData"] as byte[];
                    if (photo != null)
                        model.Photo = photo;

                    user.Update(model);

                    Session["FileData"] = null;
                }
                catch (Exception ex)
                {
                    ViewData["EditError"] = ex.Message;
                }
            }
            else
            {
                ViewData["EditError"] = "Please, correct all errors.";
            }

            return UserRowPartial();
        }

        public ActionResult DeleteUser(UserViewModel model, string selectedIds)
        {
            if (!string.IsNullOrEmpty(selectedIds))
            {
                var ids = new List<Guid>();
                foreach (var item in selectedIds.Split(','))
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        ids.Add(new Guid(item));
                    }
                }

                try
                {
                    if (ids.Count > 0)
                    {
                        user.Delete(ids);
                    }
                }
                catch (Exception ex)
                {

                }
            }

            return UserRowPartial();
        }
        #endregion

        #region Paging
        public ActionResult UserRowPartial()
        {
            var viewModel = GridViewExtension.GetViewModel("gvUser");
            if (viewModel == null)
            {
                viewModel = CreateGridViewModel();
            }
            return CustomBindingCore(viewModel);
        }

        public ActionResult ApplyFilterExpressionPartial(string filterExpression)
        {
            var viewModel = GridViewExtension.GetViewModel("gvUser");
            viewModel.FilterExpression = filterExpression;
            return CustomBindingCore(viewModel);
        }

        public ActionResult UserSortingRowPartial(GridViewColumnState column, bool reset)
        {
            var viewModel = GridViewExtension.GetViewModel("gvUser");

            viewModel.SortBy(column, reset);
            return CustomBindingCore(viewModel);
        }

        private GridViewModel CreateGridViewModel()
        {
            var viewModel = new GridViewModel();
            viewModel.KeyFieldName = "ID";
            viewModel.Columns.Add("UserName");
            viewModel.Columns.Add("FullName");
            viewModel.Columns.Add("Email");
            viewModel.Columns.Add("PhoneNumber");
            return viewModel;
        }

        public ActionResult UserPagingRowPartial(GridViewPagerState pager)
        {
            var viewModel = GridViewExtension.GetViewModel("gvUser");
            viewModel.Pager.Assign(pager);
            return CustomBindingCore(viewModel);
        }

        public ActionResult UserFilteringRowPartial(GridViewColumnState column)
        {
            var viewModel = GridViewExtension.GetViewModel("gvUser");
            viewModel.Columns[column.FieldName].Assign(column);
            return CustomBindingCore(viewModel);
        }

        PartialViewResult CustomBindingCore(GridViewModel gridViewModel)
        {
            gridViewModel.ProcessCustomBinding(
                UserBindingHandler.GetDataRowCount,
                UserBindingHandler.GetData
            );

            return PartialView("UserGridPartial", gridViewModel);
        }
        #endregion

    }
}
